#!/bin/bash
#
# MikoPBX - free phone system for small business
# Copyright © 2017-2023 Alexey Portnov and Nikolay Beketov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
#
if test -w /dev/ttyS0 && ! /bin/busybox setserial -g /dev/ttyS0 | /bin/grep -q unknown; then
  exec </dev/console > >(/bin/busybox tee /dev/ttyS0) 2>&1
else
  exec </dev/console >/dev/console 2>/dev/console;
fi

echo " - Start ${0}";
# Starting the syslog daemon with specific options
/sbin/syslogd -S -C512

# Setting environment variables for home directory and path
HOME=/
PATH=/sbin:/bin:/usr/sbin:/usr/bin

export HOME PATH
echo ' - Create system dirs'

# Creating necessary directories and symbolic links for the system
mkdir -p /dev/pts \
  /dev/bus /tmp \
  /ultmp \
  /offload \
  /cf/conf \
  /var/etc \
  /var/spool/cron \
  /var/spool/cron/crontabs \
  /var/lib/php/session

chmod 777 /tmp
ln -s /offload/rootfs/usr /usr
ln -s /sys/bus/usb /dev/bus/usb

# Creating device nodes for null and initctl
rm -rf /dev/null
mknod /dev/null c 1 3
mknod /dev/initctl p

# Starting udev to manage the /dev directory dynamically
/sbin/udevd --daemon
/sbin/udevadm trigger
/sbin/udevadm settle

# Waiting for device setup to complete
sleep 5

# Mounting devpts which is a pseudo file system used to access pseudo terminals
mount -t devpts -o gid=5,mode=620 devpts /dev/pts

# Setting up loopback network interface
/bin/busybox ifconfig lo 127.0.0.1

# Disable password login for root user
# The login will be configured later when setting the password
/bin/busybox passwd -l root

# Setting kernel parameters
/sbin/sysctl -w kernel.printk="3 4 1 6" >/dev/null 2>/dev/null
/sbin/sysctl -w net.ipv6.conf.all.disable_ipv6=1 >/dev/null 2>/dev/null
/sbin/sysctl vm.overcommit_memory=1 >/dev/null 2>/dev/null
/sbin/sysctl net.core.somaxconn=65535 >/dev/null 2>/dev/null

# RAID setup
mdadmPath=$(/sbin/which mdadm)
if [ -n "$mdadmPath" ]; then
  # Initial array setup
  "$mdadmPath" --detail --scan | /bin/busybox cut -d ' ' -f 2 | /bin/xargs "$mdadmPath" --stop >/dev/null 2>/dev/null
  "$mdadmPath" --assemble --scan
  mkdir -p /etc/mdadm
  # Config generation
  echo "DEVICE partitions" >/etc/mdadm/mdadm.conf
  arrList=$("$mdadmPath" --detail --scan | /bin/busybox cut -d ' ' -f 2)
  for mdName in $arrList; do
    # Getting array index
    mdIndex=$("$mdadmPath" --detail --scan --verbose | /bin/busybox grep "$mdName" | /bin/busybox awk '/ARRAY/ {print}' | /bin/busybox sed -r 's/[[:alnum:]]+=/\n&/g' | /bin/busybox grep name | /bin/busybox awk -F'[=]|[:]' ' { print $3} ')
    dstDev="md${mdIndex}"
    srcDev=$(/bin/busybox basename "$mdName")
    "$mdadmPath" --detail --scan --verbose | /bin/busybox grep 'ARRAY' | /bin/busybox grep "$srcDev" | /bin/busybox sed "s/\/${srcDev}/\/${dstDev}/g" >>/etc/mdadm/mdadm.conf
  done
  # Stopping all arrays
  "$mdadmPath" --detail --scan | /bin/busybox cut -d ' ' -f 2 | /bin/xargs "$mdadmPath" --stop >/dev/null 2>/dev/null

  # Assembling arrays with correct config
  "$mdadmPath" --assemble --scan
fi
# RAID END

# Source shell functions for use later in the script
. /sbin/shell_functions.sh

# Running a system check for updates
echo
echo " - Start /sbin/check-update-pbx script ..."
/sbin/check-update-pbx

# If the system is rebooting, terminate the script
if [ -f /tmp/rebooting ]; then
  exit 0
fi

# Mounting offload and configuration directories
echo
echo " - Start /sbin/mountoffload script..."
if /sbin/mountoffload; then
    echo " - Continuing boot process."
    echo " - Start /etc/rc/mountconfdir script..."
    if /etc/rc/mountconfdir; then
      echo " - Continuing boot process."
      # Booting up the system
      /etc/rc/bootup 2>/dev/null
    else
      echo " - Failed to mount conf, halting boot process."
      sleep 15;
      exit 1
    fi
else
    echo " - Failed to mount offload, halting boot process."
    sleep 15;
    exit 1
fi